﻿using BuildStatus.Web.BuildServer;
using BuildStatus.Web.Properties;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Http;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace BuildStatus.Web
{
    [Authorize]
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected bool VerifyConfiguration()
        {
            if (string.IsNullOrEmpty(BuildSettings.Settings.TFSUri))
                return false;

            return true;
        }

        protected string GetEmbeddedHtml()
        {
            if (string.IsNullOrEmpty(BuildSettings.Settings.EmbeddedHtmlFile))
                return "";

            string path = Path.GetDirectoryName(BuildSettings.Settings.EmbeddedHtmlFile);
            string searchPattern = Path.GetFileName(BuildSettings.Settings.EmbeddedHtmlFile);

            StringBuilder htmlBuilder = new StringBuilder();
            htmlBuilder.AppendLine($"<div class=\"TeamProject {BuildSettings.Settings.EmbeddedHtmlFile}\">");
            htmlBuilder.AppendLine($"<h2 class=\"Name ng-binding\">{BuildSettings.Settings.EmbeddedHtmlTitle}</h2>");

            List<string> files = Directory.GetFiles(path, searchPattern).OrderByDescending(x => x).ToList();
            foreach (string filename in files)
            {
                try
                {
                    if (File.Exists(filename))
                    {
                        string embeddedHtml = File.ReadAllText(filename);
                        htmlBuilder.AppendLine(embeddedHtml);
                    }
                }
                catch { }
            }

            htmlBuilder.AppendLine($"</div>");
            return htmlBuilder.ToString();
        }
    }
}